package com.hotacorp.opencloud.userservice.service.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotacorp.opencloud.userservice.dao.SysDepartmentDao;
import com.hotacorp.opencloud.userservice.entity.SysDepartmentEntity;
import com.hotacorp.opencloud.userservice.service.SysDepartmentService;

/**
 * 部门管理接口实现
 * @author lwg
 *
 */
@Service("sysDepartmentService")
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentDao, SysDepartmentEntity> implements SysDepartmentService {

	@Override
	public List<SysDepartmentEntity> list(Map<String, Object> params) {
		QueryWrapper<SysDepartmentEntity> wrap = new QueryWrapper<SysDepartmentEntity>();
		if (params.containsKey("tenantid")) {
			wrap.eq("tenantid", params.get("tenantid"));
		}
		if (params.containsKey("parentid")) {
			wrap.eq("parentid", params.get("parentid"));
		}
		return super.list(wrap);
	}

	@Override
	public int updateById(SysDepartmentEntity sysDepartment, Long tenantid) {
		SysDepartmentEntity ddd = baseMapper.selectById(sysDepartment.getDepid());
		if (ddd != null && ddd.getTenantid().longValue() == tenantid.longValue()) {
			Set<Long> dddd = getParentId(sysDepartment.getParentid());
			if (dddd.contains(ddd.getDepid())) return 2;//把上级部门改为现有上级部门的子部门是不允许的
			boolean ooo = super.updateById(sysDepartment);
			if (ooo) {
				return 0;//改改成功
			} else {
				return 3;//更新数据失败
			}
		} else {
			return 1;//修改不是本租户的部门
		}
	}
	
	private Set<Long> getParentId(Long depid) {
		Set<Long> ret = new HashSet<Long>();
		ret.add(depid);
		setParent(ret, depid);
		return ret;
	}

	private void setParent(Set<Long> ret, Long depid) {
		SysDepartmentEntity ddd = baseMapper.selectById(depid);
		if (ddd != null) {
			ret.add(ddd.getParentid());
			setParent(ret, ddd.getParentid());
		}
	}

	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList, Long tenantid) {
		QueryWrapper<SysDepartmentEntity> wrap = new QueryWrapper<SysDepartmentEntity>();
		wrap.eq("tenantid", tenantid);
		wrap.in("depid", idList);
		int a = baseMapper.delete(wrap);
		if (a > 0) {
			return true;
		} else {
			return false;
		}
	}
}